import { LocationStateType } from '@/components/AuthRoute';
import store from '@/store';
import { Toast } from 'antd-mobile';
import axios from 'axios';
import history from './history';
import { cleartoken, gettoken, settoken } from './storage';

export const baseURL = 'http://geek.itheima.net';
console.log(history.push, '345456356');

// 创建 axios 实例
const http = axios.create({
  baseURL: baseURL,
  timeout: 5000,
});

// 请求拦截器
http.interceptors.request.use(
  function (config) {
    const { token } = gettoken();
    if (config.headers && token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use(
  function (response) {
    return response.data;
  },
  async function (error) {
    console.dir(error);
    if (!error.response) {
      Toast.show({ content: '网络劈叉了' });
    }
    if (error.response.status !== 401) {
      Toast.show({ content: error.response.data.message });
    } else {
      // token刷新
      const refresh_token = gettoken().refresh_token;
      if (refresh_token) {
        try {
          const res = await axios({
            url: baseURL + '/v1_0/authorizations',
            method: 'put',
            headers: {
              Authorization: `Bearer ${refresh_token}`,
            },
          });
          console.log(res.data.data.token);
          const tokenInfo = { token: res.data.data.token, refresh_token };
          store.dispatch({
            type: 'user/saveAuth',
            payload: tokenInfo,
          });
          settoken(tokenInfo);
          return http(error.config);
        } catch (error) {
          cleartoken();
          store.dispatch({
            type: 'user/saveAuth',
            payload: {} as any,
          });
          history.push('/login', {
            from: history.location.pathname,
          } as LocationStateType);
        }
      } else {
        history.push('/login', {
          from: history.location.pathname,
        } as LocationStateType);
      }
      Toast.show({ content: '登录超时，请重新登录' });
    }
    return Promise.reject(error);
  }
);

// 导出 axios 实例
export default http;
